<%
layout("/layouts/platform.html"){
%>
<style>
    .padding10 {
        padding: 5px;
    }

    .self-send {
        color: #1E9FFF;
    }

    .server-send {
        color: #FF5722;
    }

    .content-main {
        height: 500px;
        overflow: auto;
    }

    .server-send-title {
        font-weight: bold;
        font-size: 12px;
    }

</style>
<div class="layui-row" id="container">
    <div class="layui-card">
        <div class="layui-card-header">简介</div>
        <div class="layui-card-body">
            Websocket是一种用于 HTML5 浏览器的实时通讯协议，可以做到数据的实时推送，可适用于广泛的工作环境。
            WebSocket 使得客户端和服务器之间的数据交换变得更加简单，允许服务端主动向客户端推送数据。在 WebSocket API
            中，浏览器和服务器只需要完成一次握手，两者之间就直接可以创建持久性的连接，并进行双向数据传输
        </div>
    </div>

    <div class="layui-row layui-col-space15">
        <div class="layui-col-md4">

            <div class="layui-card">
                <div class="layui-card-header" style="padding-bottom: 10px">
                    <form class="layui-form" onsubmit="return false;">
                        <div class="layui-inline">
                            <label class="layui-form-md" style="width:20px">ws://</label>
                            <div class="layui-input-inline" style="width: 100px">
                                <input type="text" v-model="webSocket.ip" placeholder="测试IP地址" autocomplete="off"
                                       class="layui-input">
                            </div>
                            <div class="layui-input-inline" style="width: 60px">
                                <input type="text" v-model="webSocket.port" placeholder="端口号" autocomplete="off"
                                       class="layui-input">
                            </div>
                            <button type="submit"
                                    :class="{'layui-btn':true,  'layui-btn-normal':!disabled.link,'layui-btn-disabled':disabled.link}"
                                    :disabled="disabled.link" @click="link">链接
                            </button>
                            <button type="reset"
                                    :class="{'layui-btn':true,  'layui-btn-primary':!disabled.close,'layui-btn-disabled':disabled.close}"
                                    :disabled="disabled.close" @click="close">断开
                            </button>
                        </div>
                    </form>
                </div>
                <div class="layui-card-body">
                    <div class="memo">
                        <p>1、连接格式为 ws://IP或域名:端口（示例ws://127.0.0.1:8800）</p>
                    </div>
                    <form class="layui-form layui-form-pane" onsubmit="return false;">
                        <div class="layui-form-item layui-form-text">
                            <label class="layui-form-label">发送的内容</label>
                            <div class="layui-input-block">
                                <textarea v-model="message" placeholder="请输入发送的内容" class="layui-textarea"></textarea>
                            </div>
                        </div>

                        <div class="layui-form-item layui-form-text">
                            <button type="button" @click="sendMsg"
                                    :class="{'layui-btn':true, 'layui-btn-fluid':true, 'layui-btn-danger':!disabled.send,'layui-btn-disabled':disabled.send}"
                                    :disabled="disabled.send">发送（Enter）
                            </button>
                        </div>
                    </form>
                    <div class="padding10">
                        <button class=" layui-btn-sm" :class="{'layui-btn':true,  'layui-btn-primary':true,}"
                                @click="saveMsg">保存消息
                        </button>
                        <button class=" layui-btn-sm" :class="{'layui-btn':true,  'layui-btn-primary':true,}"
                                @click="clearMsg">清空消息
                        </button>
                    </div>
                </div>

            </div>
        </div>
        <div class="layui-col-md8">
            <div class="layui-card">
                <div class="layui-card-header">消息中心</div>
                <div class="layui-card-body">
                    <div class="content-main" id="messageView"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script id="messageTpl" type="text/html">
    <div class="padding10">
        {{# if(d.functionCode == 0){ }}
        <p class="self-send">你&nbsp;{{d.time}}</p>
        <p>{{d.msg}}</p>
        {{# } else if(d.functionCode == 1){ }}
        <p class="server-send">服务器&nbsp;{{d.time}}</p>
        <p>服务端返回你发的消息：{{d.msg}}</p>
        {{# } else if(d.functionCode == 2){ }}
        <p class="server-send">服务器&nbsp;{{d.time}}</p>
        <p><span class="server-send-title">服务端主动向你推送：</span>{{d.msg}}</p>
        {{# } else if(d.functionCode == 3 ){ }}
        <p class="server-send">服务器&nbsp;{{d.time}}</p>
        <p>{{d.msg}}</p>
        {{# } }}

    </div>
</script>

<script type="text/javascript">
    var vm;
    layui.use(["form", "laytpl","websocket"], function () {
        vm = new Vue({
            el: '#container',
            data: function () {
                return {
                    form: layui.form,
                    laytpl: layui.laytpl,
                    websocket: layui.websocket,
                    webSocket: {
                        ip: '127.0.0.1',
                        port: '8080',
                    },
                    message: '',
                    disabled: {
                        send: true,
                        link: false,
                        close: true,
                    },
                    socket: null,
                }
            },
            watch: {
                "webSocket.ip": {
                    handler: function (val, oldVal) {
                        this.disabled.link = !(val && this.webSocket.port);
                    },
                },
                "webSocket.port": {
                    handler: function (val, oldVal) {
                        this.disabled.link = !(this.webSocket.ip && val);
                    },
                },
                "message": {
                    handler: function (val, oldVal) {
                        // false val 不为空 && close 为 false
                        this.disabled.send = !val.trim();
                    },
                },
            },
            mounted: function () {
                var $this = this;
                layui.jquery($this.$el).removeClass("hide").addClass("show");
                $this.initForm();
            }
            ,
            methods: {
                disabledFun: function () {
                    var $this = this;
                    $this.disabled.send = true;
                    $this.disabled.link = false;
                    $this.disabled.close = true;
                },
                enableFun: function () {
                    var $this = this;
                    $this.disabled.send = false;
                    $this.disabled.link = true;
                    $this.disabled.close = false;
                },
                renderTemplate: function (data) {
                    var $this = this,
                        getTpl = document.getElementById('messageTpl').innerHTML,
                        view = document.getElementById('messageView');
                    $this.laytpl(getTpl).render(data, function (html) {
                        view.innerHTML += html;
                    });
                },
                initForm: function () {
                    var $this = this;
                    $this.form.render(null, "addForm");
                },
                close: function () {
                    var $this = this;
                    if ($this.socket) {
                        $this.socket.close();
                        $this.disabledFun();
                    }
                },
                saveMsg: function () {

                },
                clearMsg: function () {

                },
                sendMsg: function () {
                    var $this = this;
                    if ($this.socket && $this.message) {
                        $this.socket.send(JSON.stringify({"message": $this.message, "functionCode": '0'}));
                    }
                },
                getMsg: function (code, msg) {
                    return {
                        functionCode: code,
                        time: new Date().toLocaleDateString(),
                        msg: msg,
                    }
                },
                link: function () {
                    var $this = this;
                    $this.socket = new $this.websocket({
                        domain: $this.webSocket.ip,
                        port: $this.webSocket.port,
                        onInit: function (event) {
                            $this.enableFun();
                            $this.renderTemplate($this.getMsg(0, "正在与服务端握手中，等待服务器Websocket握手包..."));
                        },
                        onOpen: function (event) {
                            $this.renderTemplate($this.getMsg(0, "已经与服务端握手,收到服务器Websocket握手包..."));
                            $this.renderTemplate($this.getMsg(3, "Websocket连接已建立，正在等待数据..."));
                        },
                        onError: function (event) {
                            $this.renderTemplate($this.getMsg(0, "与服务端建立握手失败；错误原因：" + event));
                        },
                        onSend: function (result) {
                            result = JSON.parse(result);
                            $this.renderTemplate($this.getMsg(result.functionCode, result.message));
                        },
                        onclose: function (event) {
                            $this.disabledFun();
                            $this.renderTemplate($this.getMsg(3, "与服务器断开连接"));
                        },
                        onMessage: function (result) {
                            result = JSON.parse(result);
                            $this.renderTemplate($this.getMsg(result.functionCode, result.message));
                        }
                    });

                }
            }
        })
        ;
    });
</script>

<%}%>